{% extends "base.html" %}
{% load app_tags %}

{% block title %}
  Create - Yamtrack
{% endblock title %}

{% block content %}
  <div class="mx-auto max-w-4xl">
    <div class="mb-8">
      <h1 class="text-3xl font-bold mb-2">Create Custom Entry</h1>
      <p class="text-gray-400">Add a custom media entry to your collection if it's not available in the database.</p>
    </div>
    {# djlint:off #}
    <form method="post" class="space-y-6" x-data="{
      mediaType: 'tv',
      placeholderHtml: null,

      init() {
        // Store the initial placeholder HTML
        this.placeholderHtml = document.getElementById('image-preview').innerHTML;
      },

      updateImagePreview(input) {
        const previewDiv = document.getElementById('image-preview');
        const imageUrl = input.value.trim();

        if (imageUrl) {
          // Clear the preview div
          previewDiv.innerHTML = '';

          // Create the image element
          const img = document.createElement('img');
          img.alt = 'Preview';
          img.className = 'w-full h-full object-cover';
          img.src = imageUrl;

          // Handle image load error
          img.onerror = function() {
            previewDiv.innerHTML = document.getElementById('error-icon').innerHTML;
          };

          // Add the image to the preview div
          previewDiv.appendChild(img);
        } else {
          // Restore the default placeholder icon
          previewDiv.innerHTML = this.placeholderHtml;
        }
      },
    
      showField(field) {
        // TV Show fields
        if (this.mediaType === 'tv') {
          return ['title', 'image', 'score', 'status', 'notes'].includes(field);
        }
    
        // Season fields
        else if (this.mediaType === 'season') {
          return ['parentShow', 'image', 'seasonNumber', 'score', 'status', 'notes'].includes(field);
        }
    
        // Episode fields
        else if (this.mediaType === 'episode') {
          return ['parentSeason', 'image', 'episodeNumber', 'endDate'].includes(field);
        }
    
        // Movie, Anime, Manga, Game, Book fields
        else {
          return ['title', 'image', 'score', 'progress', 'status', 'startDate', 'endDate', 'notes'].includes(field);
        }
      },
    
      getProgressLabel() {
        if (this.mediaType === 'anime') return 'Progress (Episodes)';
        if (this.mediaType === 'manga') return 'Progress (Chapters)';
        if (this.mediaType === 'game') return 'Progress (Play Time)';
        if (this.mediaType === 'book') return 'Progress (Pages)';
        return 'Progress';
      },
    
      validateForm() {
        // Validate parent TV selection for Season
        if (this.mediaType === 'season') {
          const parentTvId = document.getElementById('parent-tv-id').value;
          if (!parentTvId) {
            alert('Please select a parent TV show from the dropdown');
            return false;
          }
        }
    
        // Validate parent Season selection for Episode
        if (this.mediaType === 'episode') {
          const parentSeasonId = document.getElementById('parent-season-id').value;
          if (!parentSeasonId) {
            alert('Please select a parent Season from the dropdown');
            return false;
          }
        }
    
        return true;
      }
    }" @submit.prevent="validateForm() && $event.target.submit()">
    {# djlint:on #}
    {% csrf_token %}
    <input type="hidden" name="media_type" :value="mediaType">

    <div class="bg-[#2a2f35] rounded-lg p-6">
      <div class="grid gap-6">
        <div x-cloak>
          <label class="block text-sm font-medium mb-2 text-gray-300">Media Type</label>
          <div class="grid grid-cols-2 sm:grid-cols-4 gap-2">
            {% for media_type in media_types %}
              <button type="button"
                      @click="mediaType = '{{ media_type }}'"
                      :class="mediaType === '{{ media_type }}' ? 'bg-indigo-600 border-indigo-500 text-white' : 'border-gray-600 text-gray-300 hover:bg-[#39404b]'"
                      class="flex items-center gap-2 p-3 rounded-md border transition-colors cursor-pointer">
                {% icon media_type is_active=False %}
                <span class="text-sm font-medium">{{ media_type|media_type_readable }}</span>
              </button>
            {% endfor %}
          </div>
        </div>

        <!-- Title field (TV, Movie, Anime, Manga, Game, Book) -->
        <div x-show="showField('title')">
          <label class="block text-sm font-medium mb-2 text-gray-300">Title</label>
          <input class="w-full p-2 bg-[#39404b] rounded-md text-white border border-gray-600 focus:outline-none focus:ring-2 focus:ring-[#4a9eff] appearance-none"
                 placeholder="Enter title"
                 name="title"
                 type="text"
                 value="">
        </div>

        <!-- Parent TV Show field (Season) -->
        <div x-show="showField('parentShow')">
          <label class="block text-sm font-medium mb-2 text-gray-300">Parent TV Show</label>
          <div class="relative">
            <div class="relative">
              <input id="parent-tv-input"
                     class="w-full p-2 pl-9 bg-[#39404b] rounded-md text-white border border-gray-600 focus:outline-none focus:ring-2 focus:ring-[#4a9eff] appearance-none"
                     placeholder="Search for a TV show..."
                     name="q"
                     type="text"
                     autocomplete="off"
                     hx-get="{% url 'search_parent_tv' %}"
                     hx-trigger="keyup changed delay:300ms"
                     hx-target="#parent-tv-results">
              <!-- Hidden input to store the selected TV ID -->
              <input id="parent-tv-id" name="parent_tv" type="hidden">
              {% include "app/icons/magnifying-glass.svg" with classes="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" %}
            </div>
            <div id="parent-tv-results"></div>
          </div>
        </div>

        <!-- Season Number field (Season) -->
        <div x-show="showField('seasonNumber')">
          <label class="block text-sm font-medium mb-2 text-gray-300">Season Number</label>
          <div class="relative">
            <input min="1"
                   max="999"
                   class="w-full p-2 pr-12 bg-[#39404b] rounded-md text-white border border-gray-600 focus:outline-none focus:ring-2 focus:ring-[#4a9eff] [appearance:textfield] [&amp;::-webkit-outer-spin-button]:appearance-none [&amp;::-webkit-inner-spin-button]:appearance-none"
                   name="season_number"
                   type="number"
                   value="1">
            <div class="absolute inset-y-0 right-0 flex flex-col border-l border-gray-600">
              <button type="button"
                      onclick="this.parentElement.previousElementSibling.stepUp()"
                      class="flex-1 px-2 hover:bg-gray-700 transition-colors rounded-tr-md border-t border-r border-gray-600 group">
                {% include "app/icons/chevron-up.svg" with classes="w-3.5 h-3.5" %}
              </button>
              <button type="button"
                      onclick="this.parentElement.previousElementSibling.stepDown()"
                      class="flex-1 px-2 hover:bg-gray-700 transition-colors rounded-br-md border-b border-r border-gray-600 group">
                {% include "app/icons/chevron-down.svg" with classes="w-3.5 h-3.5" %}
              </button>
            </div>
          </div>
        </div>

        <!-- Parent Season field (Episode) -->
        <div x-show="showField('parentSeason')">
          <label class="block text-sm font-medium mb-2 text-gray-300">Parent Season</label>
          <div class="relative">
            <div class="relative">
              <input id="parent-season-input"
                     class="w-full p-2 pl-9 bg-[#39404b] rounded-md text-white border border-gray-600 focus:outline-none focus:ring-2 focus:ring-[#4a9eff] appearance-none"
                     placeholder="Search for a season..."
                     name="q"
                     type="text"
                     autocomplete="off"
                     hx-get="{% url 'search_parent_season' %}"
                     hx-trigger="keyup changed delay:300ms"
                     hx-target="#parent-season-results">
              <!-- Hidden input to store the selected Season ID -->
              <input id="parent-season-id" name="parent_season" type="hidden">
              {% include "app/icons/magnifying-glass.svg" with classes="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" %}
            </div>
            <div id="parent-season-results"></div>
          </div>
        </div>

        <!-- Episode Number field (Episode) -->
        <div x-show="showField('episodeNumber')">
          <label class="block text-sm font-medium mb-2 text-gray-300">Episode Number</label>
          <div class="relative">
            <input min="1"
                   max="999"
                   class="w-full p-2 pr-12 bg-[#39404b] rounded-md text-white border border-gray-600 focus:outline-none focus:ring-2 focus:ring-[#4a9eff] [appearance:textfield] [&amp;::-webkit-outer-spin-button]:appearance-none [&amp;::-webkit-inner-spin-button]:appearance-none"
                   name="episode_number"
                   type="number"
                   value="1">
            <div class="absolute inset-y-0 right-0 flex flex-col border-l border-gray-600">
              <button type="button"
                      onclick="this.parentElement.previousElementSibling.stepUp()"
                      class="flex-1 px-2 hover:bg-gray-700 transition-colors rounded-tr-md border-t border-r border-gray-600 group">
                {% include "app/icons/chevron-up.svg" with classes="w-3.5 h-3.5" %}
              </button>
              <button type="button"
                      onclick="this.parentElement.previousElementSibling.stepDown()"
                      class="flex-1 px-2 hover:bg-gray-700 transition-colors rounded-br-md border-b border-r border-gray-600 group">
                {% include "app/icons/chevron-down.svg" with classes="w-3.5 h-3.5" %}
              </button>
            </div>
          </div>
        </div>

        <!-- Image URL field (All types) -->
        <div x-show="showField('image')">
          <label class="block text-sm font-medium mb-2 text-gray-300">Image URL</label>
          <div class="flex gap-4">
            <div class="flex-1">
              <input class="w-full p-2 bg-[#39404b] rounded-md text-white border border-gray-600 focus:outline-none focus:ring-2 focus:ring-[#4a9eff] appearance-none"
                     name="image"
                     placeholder="Enter image URL"
                     type="url"
                     value=""
                     x-on:input="updateImagePreview($event.target)">
            </div>
            <div id="image-preview"
                 class="w-20 h-20 rounded-md overflow-hidden bg-[#39404b] border border-gray-600 flex items-center justify-center">
              {% include "app/icons/image.svg" with classes="w-8 h-8 text-gray-500" %}
            </div>
            <!-- Hidden error icon template -->
            <div id="error-icon" class="hidden">
              {% include "app/icons/circle-x.svg" with classes="w-8 h-8 text-red-500" %}
            </div>
          </div>
        </div>

        <!-- Score field (TV, Movie, Anime, Manga, Game, Book, Season) -->
        <div x-show="showField('score')">
          <label class="block text-sm font-medium mb-2 text-gray-300">Score</label>
          <div class="relative">
            <input min="0"
                   max="10"
                   class="w-full p-2 pr-12 bg-[#39404b] rounded-md text-white border border-gray-600 focus:outline-none focus:ring-2 focus:ring-[#4a9eff] [appearance:textfield] [&amp;::-webkit-outer-spin-button]:appearance-none [&amp;::-webkit-inner-spin-button]:appearance-none"
                   name="score"
                   type="number"
                   placeholder="0-10">
            <div class="absolute inset-y-0 right-0 flex flex-col border-l border-gray-600">
              <button type="button"
                      onclick="this.parentElement.previousElementSibling.stepUp()"
                      class="flex-1 px-2 hover:bg-gray-700 transition-colors rounded-tr-md border-t border-r border-gray-600 group">
                {% include "app/icons/chevron-up.svg" with classes="w-3.5 h-3.5" %}
              </button>
              <button type="button"
                      onclick="this.parentElement.previousElementSibling.stepDown()"
                      class="flex-1 px-2 hover:bg-gray-700 transition-colors rounded-br-md border-b border-r border-gray-600 group">
                {% include "app/icons/chevron-down.svg" with classes="w-3.5 h-3.5" %}
              </button>
            </div>
          </div>
        </div>

        <!-- Progress field (Movie, Anime, Manga, Game, Book) -->
        <div x-show="showField('progress')">
          <label class="block text-sm font-medium mb-2 text-gray-300"
                 x-text="getProgressLabel()">Progress</label>

          <div class="relative">
            <input class="w-full p-2 pr-12 bg-[#39404b] rounded-md text-white border border-gray-600 focus:outline-none focus:ring-2 focus:ring-[#4a9eff] appearance-none"
                   name="progress"
                   x-bind:type="mediaType === 'game' ? 'text' : 'number'"
                   x-bind:placeholder="mediaType === 'game' ? 'hh:mm' : ''"
                   x-bind:min="mediaType !== 'game' ? 0 : null"
                   x-bind:max="mediaType !== 'game' ? 99999 : null"
                   x-bind:class="{'[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none': mediaType !== 'game'}"
                   x-bind:value="mediaType !== 'game' ? '0' : ''">

            <div x-show="mediaType !== 'game'"
                 class="absolute inset-y-0 right-0 flex flex-col border-l border-gray-600">
              <button type="button"
                      onclick="this.parentElement.previousElementSibling.stepUp()"
                      class="flex-1 px-2 hover:bg-gray-700 transition-colors rounded-tr-md border-t border-r border-gray-600 group">
                {% include "app/icons/chevron-up.svg" with classes="w-3.5 h-3.5" %}
              </button>
              <button type="button"
                      onclick="this.parentElement.previousElementSibling.stepDown()"
                      class="flex-1 px-2 hover:bg-gray-700 transition-colors rounded-br-md border-b border-r border-gray-600 group">
                {% include "app/icons/chevron-down.svg" with classes="w-3.5 h-3.5" %}
              </button>
            </div>
          </div>
        </div>

        <!-- Status field (TV, Movie, Anime, Manga, Game, Book, Season) -->
        <div x-show="showField('status')">
          <label class="block text-sm font-medium mb-2 text-gray-300">Status</label>
          <div class="relative">
            <select class="w-full p-2 bg-[#39404b] rounded-md text-white border border-gray-600 focus:outline-none focus:ring-2 focus:ring-[#4a9eff] appearance-none"
                    name="status">
              {% for status in Status.values %}<option value="{{ status }}">{{ status }}</option>{% endfor %}
            </select>
            <div class="absolute inset-y-0 right-2 flex items-center pointer-events-none">
              {% include "app/icons/chevron-down.svg" with classes="w-4 h-4" %}
            </div>
          </div>
        </div>

        <!-- Start Date field (Movie, Anime, Manga, Game, Book) -->
        <div x-show="showField('startDate')">
          <label class="block text-sm font-medium mb-2 text-gray-300">Start Date</label>
          <input class="w-full p-2 bg-[#39404b] rounded-md text-white border border-gray-600 focus:outline-none focus:ring-2 focus:ring-[#4a9eff] appearance-none"
                 name="start_date"
                 type="date"
                 value="">
        </div>

        <!-- End Date field (Episode, Movie, Anime, Manga, Game, Book) -->
        <div x-show="showField('endDate')">
          <label class="block text-sm font-medium mb-2 text-gray-300">End Date</label>
          <input class="w-full p-2 bg-[#39404b] rounded-md text-white border border-gray-600 focus:outline-none focus:ring-2 focus:ring-[#4a9eff] appearance-none"
                 name="end_date"
                 type="date"
                 value="">
        </div>

        <!-- Notes field (TV, Movie, Anime, Manga, Game, Book, Season) -->
        <div x-show="showField('notes')">
          <label class="block text-sm font-medium mb-2 text-gray-300">Notes</label>
          <textarea class="w-full p-2 bg-[#39404b] rounded-md text-white border border-gray-600 focus:outline-none focus:ring-2 focus:ring-[#4a9eff] appearance-none"
                    rows="4"
                    name="notes"
                    placeholder="Add any notes or comments..."></textarea>
        </div>
      </div>

      <button type="submit"
              class="flex items-center mt-5 px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 transition-colors text-sm cursor-pointer">
        {% include "app/icons/save.svg" with classes="w-4 h-4 mr-2" %}
        Create Entry
      </button>
    </div>
  </form>
</div>
{% endblock content %}
